const { connection, requestSql } = require("../database/db")
const moment = require("moment")   //格式化时间模块 cnpm install moment --save
const bcrypt = require('bcryptjs'); //加密模块  cnpm install bcryptjs --save
const salt = bcrypt.genSaltSync(10);
const svgCaptcha = require("svg-captcha") //cnpm install svg-captcha --save
const random = require('string-random');  //cnpm install string-random --save
const JWT = require('./token')
console.log(JWT);
var tempCaptcha = "" //定义一个全局变量
var tempPhoneCode = "" //定义一个全局变量临时存储短信验证码
//暴露一个用户列表controller
exports.UserList = async (req, res) => {
    //localhost:3000/api/userlist?page=1&size=10
    console.log(req.query); //{ page: '1', size: '2' }
    let page = req.query.page || 1   //请求页数
    let size = req.query.size || 10  //每页几条数据
    //SELECT * from dsc_user WHERE is_show=1 ORDER BY id ASC LIMIT 2,1
    let sql = `SELECT * from dsc_user WHERE is_show=1 ORDER BY id ASC LIMIT ${(page - 1) * size},${size}`
    let result = await requestSql(sql)

    let sqlCount = `SELECT COUNT(*) FROM dsc_user WHERE is_show=1`
    let resultCount = await requestSql(sqlCount)
    let total = resultCount[0]['COUNT(*)']
    console.log(resultCount[0]['COUNT(*)']); //[ RowDataPacket { 'COUNT(*)': 3 } ]
    res.json({
        status: 200,
        page: page,
        size: size,
        total: total,
        data: result
    })
}

//用户注册
//用户名不能重复注册
//手机号不能重复注册
exports.UserRegister = (req, res) => {
    console.log(req.body);  //获取post发送的数据
    //{username:"zhangsan",password:"123456",phone:"13673618137"}
    let username = req.body.username
    let password = req.body.password
    let phone = req.body.phone

    let sql_name = `SELECT username from dsc_user WHERE username=? AND is_show=1`
    let nowTime = moment().format("YYYY-MM-DD HH:mm:ss")
    console.log(nowTime);
    connection.query(sql_name, username, (err, result_name) => {
        if (err) {
            return res.json({
                msg: "注册失败1",
                data: err
            })
        }
        console.log(result_name);
        //如果result_name为空说明用户名可用，否则用户名已经存在
        if (result_name == "") {  //如果条件成立，说明用户名可用
            //在验证手机号是否可用
            let sql_phone = `SELECT username from dsc_user WHERE phone=? AND is_show=1`
            connection.query(sql_phone, phone, (err, result_phone) => {
                if (err) {
                    return res.json({
                        msg: "注册失败2",
                        data: err
                    })
                }
                console.log(result_phone);  //如果result_phone为空说明该手机号可用，否则手机号已经存在
                if (result_phone == "") { //如果条件成立，可以去注册了
                    //INSERT INTO dsc_user SET username="lisi",sex="保密"
                    let sql_register = `INSERT INTO dsc_user SET username=?,password=?,phone=?,is_show=1,create_time="${nowTime}"`
                    let hashPassword = bcrypt.hashSync(password, salt);
                    connection.query(sql_register, [username, hashPassword, phone], (err, result) => {
                        if (err) {
                            return res.json({
                                msg: "注册失败3",
                                data: err
                            })
                        }
                        // console.log(result);
                        // OkPacket {    
                        //     fieldCount: 0,
                        //     affectedRows: 1,
                        //     insertId: 7,
                        //     serverStatus: 2,
                        //     warningCount: 0,
                        //     message: '',
                        //     protocol41: true,
                        //     changedRows: 0
                        //   }
                        if (result.affectedRows == 1) {
                            return res.json({
                                msg: "注册成功",
                                status: 200,
                                data: result
                            })
                        } else {
                            return res.json({
                                msg: "注册失败4",
                                data: err
                            })
                        }
                    })
                } else {
                    return res.json({
                        msg: "该手机号已存在，请更换手机号",
                        status: 50001,
                        data: err
                    })
                }
            })
        } else {
            return res.json({
                msg: "该用户名已存在，请更换用户名",
                status: 50001,
                data: err
            })
        }
    })
}


// 用户登录接口--账号登录
exports.UserLogin = async (req, res) => {
    console.log(req.body);  //{username:"admin",password:123456}
    let username = req.body.username
    //先判断用户名是否存在
    const sql_name = `SELECT * FROM dsc_user WHERE username=? AND is_show=1`
    connection.query(sql_name, [username], (err, result) => {
        if (err) {
            return res.json({
                msg: "数据库查询失败",
                status: 500,
                data: err
            })
        }
        if (result == "") {
            return res.json({
                msg: "用户名不存在，赶快注册一个体检吧",
                status: 500,
                data: err
            })
        } else {
            //req.body.password 表单输入的密码
            //result[0].password 数据库中读取出来的密码
            const password = bcrypt.compareSync(req.body.password, result[0].password)
            console.log(password);
            if (!password) {  //如果条件成立，说明密码不对
                return res.json({
                    msg: "密码错误，请输入正确的密码",
                    status: 404
                })
            } else {
                let token = JWT.createToken({
                    username: username,
                    login: true
                })
                return res.json({
                    msg: "登录成功",
                    status: 200,
                    data: result,
                    token: token
                })
            }
        }
    })
}

//生成随机验证码
exports.SvgCaptcha = (req, res) => {
    var captcha = svgCaptcha.create({
        size: 4, //字符串长度
        ignoreChars: '0o1i', // 排除的字符
        noise: 2, // 干扰线条数
        color: true, //文字颜色
        background: '#efefef', // 背景颜色
    });
    console.log(captcha.text);
    tempCaptcha = captcha.text.toLowerCase()
    res.type('svg');
    res.status(200).send(captcha.data);
}


//获取手机短信验证码
exports.PhoneCode = async (req, res) => {
    //1、输入正确的手机号
    //2、点击获取手机验证码，发起请求
    //3、收到短信验证码
    console.log(req.body); //{phone:"13673618137"}
    let phone = req.body.phone
    //随机生成一个6位数字
    //Math.random()
    let phoneCode = ("000000" + Math.floor(Math.random() * 999999)).slice(-6)
    console.log(phoneCode);
    tempPhoneCode = phoneCode
    res.json({
        msg: "发送成功",
        status: 200,
        data: phoneCode
    })
}


// 用户登录接口--手机号获取验证码登录
// 1、如果用户首次通过手机号登录
// 用该手机号注册一个账号，用户随机生成

// 2、如果用不是首次通过手机号登录
//直接发消息
exports.phoneLogin = async (req, res) => {
    console.log("111111" + tempCaptcha); //412362
    console.log("222222" + tempPhoneCode);
    console.log(req.body);  //{ captcha: 'f7qx', phonecode: '519961', phone: '13673618137' }

    // 111111tdym
    // 222222005904
    // { captcha: 'tdym', phonecode: '005904', phone: '13673618137' }
    let captcha = req.body.captcha.toLowerCase()  //图片四位验证码
    let phone = req.body.phone     //填写的手机号
    let phonecode = req.body.phonecode
    if (captcha != tempCaptcha) {
        return res.json({
            status: 4001,
            msg: "图片验证码不正确"
        })
    } else if (phonecode != tempPhoneCode) {
        return res.json({
            status: 4001,
            msg: "短信验证码不正确"
        })
    } else {
        //判断手机号是否存在
        //如果手机号在系统中不存在，注册一个
        let sql_phone = `SELECT * FROM dsc_user WHERE phone=? AND is_show=1`
        let phone_result = await requestSql(sql_phone, phone)
        console.log(phone_result);
        if (phone_result.length == 0) { //如果条件成立说明手机号不存在
            //注册手机号
            // 随机生成一个用户
            let username = "dsc_" + random(5) + new Date().getTime()
            let nowTime = moment().format("YYYY-MM-DD HH:mm:ss")

            let sql_reg = `INSERT INTO dsc_user (username,phone,is_show,create_time) VALUES ("${username}","${phone}","1","${nowTime}")`

            let phoneResult = await requestSql(sql_reg)
            console.log(phoneResult);
            if (phoneResult.affectedRows == 1) {
                let token = JWT.createToken({
                    username: username,
                    login: true
                })
                return res.json({
                    status: 200,
                    msg: "登录成功",
                    data: phoneResult,
                    token: token
                })
            } else {
                return res.json({
                    status: 500,
                    msg: "服务器错误"
                })
            }

        } else {
            let token = JWT.createToken({
                username: phone,
                login: true
            })
            return res.json({
                status: 200,
                msg: "登录成功",
                data: [{
                    username: phone,
                    phone: phone
                }],
                token: token
            })
        }
    }
}